#include "DatabaseManager.h"
#include <iostream>

DatabaseManager& DatabaseManager::getInstance() {
    static DatabaseManager instance("smart_home.db");
    return instance;
}

DatabaseManager::DatabaseManager(const std::string& dbPath)
    : dbPath(dbPath), db(nullptr) {
    connect();
}

DatabaseManager::~DatabaseManager() {
    disconnect();
}

bool DatabaseManager::connect() {
    if (sqlite3_open(dbPath.c_str(), &db) == SQLITE_OK) {
        std::cout << "数据库连接成功" << std::endl;
        return true;
    } else {
        std::cerr << "错误：无法连接数据库" << std::endl;
        return false;
    }
}

bool DatabaseManager::disconnect() {
    if (db) {
        sqlite3_close(db);
        db = nullptr;
        std::cout << "数据库断开连接成功" << std::endl;
        return true;
    } else {
        std::cerr << "错误：数据库未连接" << std::endl;
        return false;
    }
}

bool DatabaseManager::executeQuery(const std::string& query) {
    char* errMsg = nullptr;
    if (sqlite3_exec(db, query.c_str(), nullptr, nullptr, &errMsg) == SQLITE_OK) {
        //std::cout << "查询语句执行成功" << std::endl;
        return true;
    } else {
        std::cerr << "错误: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
}

std::vector<std::vector<std::string>> DatabaseManager::fetchResults(const std::string& query) {
    std::vector<std::vector<std::string>> results;
    sqlite3_stmt* stmt;
    if (sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            std::vector<std::string> row;
            for (int i = 0; i < sqlite3_column_count(stmt); i++) {
                const char* columnText = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
                row.push_back(columnText ? columnText : "");
            }
            results.push_back(row);
        }
        sqlite3_finalize(stmt);
    } else {
        std::cerr << "错误：无法获取结果" << std::endl;
    }
    return results;
}

sqlite3* DatabaseManager::getDB() { // 实现 getDB 成员函数
    return db;
}
